package com.xyz.study.kafka.primary.consumer;

import org.apache.kafka.clients.consumer.*;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 消费者
 *
 * @author XYZ
 * @version 1.0.0
 * @date 2020/6/29
 */
public class ConsumerMain {

    private static KafkaConsumer<String, String> kafkaConsumer;

    private static String topic = "test-topic";

    static{
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.192.22:9092");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "group_id_xyz");
        kafkaConsumer = new KafkaConsumer<>(properties);
    }

    public static void main(String[] args) throws InterruptedException {
        List<String> topics = new ArrayList<>();
        topics.add(topic);
        kafkaConsumer.subscribe(topics);
        while (true){
            ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.of(1, ChronoUnit.SECONDS));
            kafkaConsumer.commitSync(Duration.of(3, ChronoUnit.SECONDS));
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords){
                System.out.println("@@@@@@@@@@@@@@@@@@@@@@@" + " : " + consumerRecord.value());
            }
            Thread.sleep(2000);
        }

    }
}
